package com.yupi.springbootinit.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @version 1.0
 * @Author moresuo
 * @Date 2024/3/6 20:54
 * @注释
 */
public class TopicConsumer {
    private static final String EXCHANGE_NAME = "topic_exchange";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("111.229.199.44");
        factory.setUsername("admin");
        factory.setPassword("admin");
        factory.setPort(5672);
        //建立连接
        Connection connection = factory.newConnection();
        //建立通道
        Channel channel = connection.createChannel();
        //声明交换机
        channel.exchangeDeclare(EXCHANGE_NAME, "topic");

        //创建前端队列
        String queueName1 = "frontend_queue";
        channel.queueDeclare(queueName1, true, false, false, null);
        //绑定交换机
        channel.queueBind(queueName1, EXCHANGE_NAME, "#.前端.#");

        //创建后端队列
        String queueName2 = "backend_queue";
        channel.queueDeclare(queueName2, true, false, false, null);
        //绑定交换机
        channel.queueBind(queueName2, EXCHANGE_NAME, "#.后端.#");

        //创建产品队列
        String queueName3 = "product_queue";
        channel.queueDeclare(queueName3, true, false, false, null);
        //绑定交换机
        channel.queueBind(queueName3, EXCHANGE_NAME, "#.产品.#");

        System.out.println(" [*] Waiting for message");

        //创建消息回调函数
        DeliverCallback xiaoaDeliverCallback=(consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [xiaoa] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
        };
        DeliverCallback xiaobDeliverCallback=(consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [xiaob] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
        };
        DeliverCallback xiaocDeliverCallback=(consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [xiaoc] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
        };
        channel.basicConsume(queueName1,true,xiaoaDeliverCallback,consumerTag -> { });
        channel.basicConsume(queueName2,true,xiaobDeliverCallback,consumerTag -> { });
        channel.basicConsume(queueName3,true,xiaocDeliverCallback,consumerTag -> { });
    }
}
